﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DBLOG.BizTalk.BizTalkExplorerServices.Entities;
using DBLOG.BizTalk.BizTalkExplorerServices.Core;
using Microsoft.BizTalk.Operations;

namespace DBLOG.BizTalk.BizTalkExplorerServices.Explorers
{
    public class ErrorExplorer : BizTalkExplorerBase
    {
        private List<BTSError> _btsErrors { get; set; }

        public List<BTSError> GetErrors()
        {
            try
            {
                _btsErrors = new List<BTSError>();

                this.GetFailedMessages();

                this.GetFailedOrchestrations();

                return _btsErrors;
            }
            catch (Exception ex)
            {
                throw new BizTalkManagementException("Could not get BizTalk errors!", ex);
            }
        }

        private void GetFailedMessages()
        {
            using (MessageExplorer messageExplorer = new MessageExplorer())
            {
                List<BizTalkMessage> messages = messageExplorer.GetSuspendedMessages();
                
                foreach (BizTalkMessage message in messages)
                {
                    this._btsErrors.Add(new BTSError()
                    {
                        Name = "Message suspended",
                        ID = message.MessageID,
                        Date = message.CreationTime,
                        BizTalkErrorType = Entities.ErrorType.Message,
                        Details = message.ErrorDescription
                    });
                }
            }
        }

        private void GetFailedOrchestrations()
        {
            using (OrchestrationExplorer orchestrationExplorer = new OrchestrationExplorer())
            {
                List<Instance> orchestrationInstances = orchestrationExplorer.GetSuspendedOrchestrationInstances();

                foreach (Instance orchestration in orchestrationInstances)
                {
                    this._btsErrors.Add(new BTSError()
                    {
                        Name = "Orchestration suspended",
                        ID = orchestration.ID,
                        Date = orchestration.CreationTime,
                        BizTalkErrorType = Entities.ErrorType.Orchestration,
                        Details = orchestration.ErrorDescription
                    });
                }
            }
        }
    }
}